package com.example.student.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.stream.Collectors;

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestDebugFilter extends OncePerRequestFilter {

    private static final Logger logger = LoggerFactory.getLogger(RequestDebugFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        
        logger.info("==== DEBUG REQUEST START ====");
        logger.info("Request: {} {}", method, requestURI);
        
        // Log all headers
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            logger.info("Headers: {}", Collections.list(headerNames)
                    .stream()
                    .map(name -> name + "=" + request.getHeader(name))
                    .collect(Collectors.joining(", ")));
        }
        
        // Special attention to login endpoint
        if (requestURI.contains("/api/auth/login")) {
            logger.info("Login request detected - ensuring it bypasses security");
        }
        
        try {
            filterChain.doFilter(request, response);
            logger.info("Response status: {}", response.getStatus());
        } catch (Exception e) {
            logger.error("Exception in filter chain: {}", e.getMessage(), e);
            throw e;
        } finally {
            logger.info("==== DEBUG REQUEST END ====");
        }
    }
} 